package com.lst.servlet;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.druid.util.StringUtils;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lst.base.entity.BaseRequest;
import com.lst.base.entity.BaseResponse;
import com.lst.common.CommCode;
import com.lst.entity.request.CompanionReqPara;
import com.lst.entity.response.CompanionResPara;
import com.lst.model.Companion;
import com.lst.model.CompanionLog;
import com.lst.service.ClientNumService;
import com.lst.service.CompanionLogService;
import com.lst.service.CompanionService;
import com.lst.service.MstDiscussService;
import com.lst.utils.RequestUtils;


/**
 * @ClassName: CompanionDetailServlet
 * @Description: 嘿哈详情接口
 * 
 */
public class CompanionDetailServlet extends BaseServlet {

	/**
	 * @Fields serialVersionUID
	 */
	private static final long serialVersionUID = 1L;

	private CompanionService companionService = ctx.getBean(CompanionService.class);
	
	private CompanionLogService companionLogService = ctx.getBean(CompanionLogService.class);
	
	private MstDiscussService mstDiscussService = ctx.getBean(MstDiscussService.class);
	
	private ClientNumService clientNumService = ctx.getBean(ClientNumService.class);
	
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		doPost(request, response);
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		CompanionResPara resPara = new CompanionResPara();

		try {
			CompanionReqPara reqPara = getReqPara(request);
		
		if(isCheckField(reqPara,resPara)){
		    Integer userid = Integer.valueOf(reqPara.getUserid());
			Integer companionId = Integer.valueOf(reqPara.getCompanionId());					
			
			Companion companion=companionService.selectByPrimaryKey(companionId);
			
			//判定是否感兴趣
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("createUser", userid);
			map.put("sourceId", companionId);
		    CompanionLog companionLog=companionLogService.queryByMap(map);
	        if(companionLog!=null){
	            	companion.setIsInterested(true);
	         }else{
	        	    companion.setIsInterested(false);
	         }
			
	      //标识是否收藏
			Map<String, Object> fmap = new HashMap<String, Object>();
			fmap.put("enabled", true);
			fmap.put("isdeleted", false);
			fmap.put("clientid", userid);
			fmap.put("actid", companion.getCompanionId());
			fmap.put("acttype", CommCode.SYSTEM_CARESEL_RANGE_COMPANION);
			fmap.put("numtype", CommCode.SYSTEM_COUNT_FAVORITE);
			Integer count = clientNumService.queryCountByMap(fmap);
			if(count>0){
				companion.setIsFavorite(true);
			}else{
				companion.setIsFavorite(false);
			}
	        
			//评论量
			Map<String, Object> anmap = new HashMap<String, Object>();
			anmap.put("tarid", companionId);
			anmap.put("type", CommCode.SYSTEM_CARESEL_RANGE_COMPANION);
			Integer companionDiscussNum = mstDiscussService.queryCountByMap(anmap);
			companion.setDiscussNum(companionDiscussNum);
			
			//根据嘿哈id查询参与者列表
			Map<String, Object> reqMap = new HashMap<String, Object>();	
			reqMap.put("sourceId",companionId);
			reqMap.put("orderByClause", "md.createDate desc");

			PageBounds pageBounds = new PageBounds(1,5);
			List<CompanionLog> companionLogList=companionLogService.queryByList(reqMap, pageBounds);
				
			resPara.setCompanionLogList(companionLogList);
			resPara.setCompanion(companion);
			resPara.setCode(CommCode.M_Y000000);
			resPara.setMessage(CommCode.M_Y000001);
		  }
		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0001);

			logger.error("doPost error: ", e);
		}
		
		try {
			response.setContentType("application/json;charset=utf-8");
			response.setHeader("pragma", "no-cache");
			response.setHeader("cache-control", "no-cache");

			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").excludeFieldsWithoutExposeAnnotation().serializeNulls().create();
			String jsonResult = gson.toJson(resPara);
	//		logger.info("CompanionDetailServlet jsonResult:" + jsonResult);

			PrintWriter out = response.getWriter();
			out.print(jsonResult);
			out.flush();
			out.close();

		//	logger.info("doPost end run(s): " + DateUtil.calLastedTime(startDate));
		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0003);

			logger.error("doPost error: ", e);
		}
	}

	@Override
	public CompanionReqPara getReqPara(HttpServletRequest request) {

		CompanionReqPara reqPara = null;

		try {
			BaseRequest baseRequest = RequestUtils.getRequestPara(request, new CompanionReqPara());

			reqPara = (CompanionReqPara) baseRequest.clone();

			String userid = request.getParameter("userid");
			String companionId = request.getParameter("companionId");
			
//			logger.info("reqPara userid:" + userid);
//			logger.info("reqPara companionId: " + companionId);
		

	        reqPara.setCompanionId(companionId);
	        reqPara.setUserid(userid);

		} catch (Exception e) {
			logger.error("getReqPara error: ", e);
		}

		return reqPara;
	}

	@Override
	public boolean isCheckField(BaseRequest reqPara, BaseResponse resPara) {
		boolean flag = false;

		CompanionReqPara cdReqPara = (CompanionReqPara) reqPara;
		BaseResponse cdResPara = (BaseResponse) resPara;

		if (StringUtils.isEmpty(cdReqPara.getCompanionId())) {
			cdResPara.setCode(CommCode.M_A000000);
			cdResPara.setMessage("结伴id为空");
		}else if (StringUtils.isEmpty(cdReqPara.getUserid())) {
			cdResPara.setCode(CommCode.M_A000000);
			cdResPara.setMessage(CommCode.M_P000002);
		} else {
			flag = true;
		}

		return  flag;
	}

}
